//
//  PageVC.swift
//  ChinaLandMark
//
//  Created by Felix Hi on 2021/6/29.
//

import SwiftUI

struct PageVC: UIViewControllerRepresentable {
    let pages = featuredLandmarks.map {
        // UIHostingController(rootView: Image($0.imageName).resizable().scaledToFill())
        UIHostingController(rootView: Image($0.imageName))
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(pages: pages)
    }
    
    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageVC = UIPageViewController(
            transitionStyle: .scroll,
            navigationOrientation: .horizontal
        )
        pageVC.dataSource = context.coordinator
        
        return pageVC
    }
    
    func updateUIViewController(_ uiViewController: UIPageViewController, context: Context) {
        uiViewController.setViewControllers([pages[0]], direction: .forward, animated: true)
    }
    
    class Coordinator: NSObject, UIPageViewControllerDataSource {
        let pages: [UIViewController]
        
        init(pages: [UIViewController]) {
            self.pages = pages
        }
        
        func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
            let currentIndex = pages.firstIndex(of: viewController)!
            if (currentIndex == 0) {
                // 当前是第一个页面
                return pages.last
            } else {
                return pages[currentIndex - 1]
            }
        }
        
        func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
            let currentIndex = pages.firstIndex(of: viewController)!
            if (currentIndex == pages.count - 1) {
                // 当前是第一个页面
                return pages.first
            } else {
                return pages[currentIndex + 1]
            }
        }
    }
}

struct PageVC_Previews: PreviewProvider {
    static var previews: some View {
        PageVC()
    }
}
